// Vuex 性能监控插件
// 这个插件演示了如何监控Vuex操作的性能

export default function createPerformancePlugin(options = {}) {
    const {
        threshold = 10,            // 性能警告阈值（毫秒）
        maxRecords = 100,          // 最大记录数量
        trackMutations = true,     // 是否跟踪mutations
        trackActions = true,       // 是否跟踪actions
        onSlowOperation = null,    // 慢操作回调
        logger = console
    } = options
    
    const performanceRecords = []
    
    return store => {
        // 添加性能监控方法到store实例
        store.getPerformanceStats = () => {
            const stats = {
                totalOperations: performanceRecords.length,
                averageTime: 0,
                slowOperations: 0,
                mutationStats: { count: 0, totalTime: 0, averageTime: 0 },
                actionStats: { count: 0, totalTime: 0, averageTime: 0 }
            }
            
            if (performanceRecords.length > 0) {
                const totalTime = performanceRecords.reduce((sum, record) => sum + record.duration, 0)
                stats.averageTime = totalTime / performanceRecords.length
                stats.slowOperations = performanceRecords.filter(r => r.duration > threshold).length
                
                const mutations = performanceRecords.filter(r => r.type === 'mutation')
                const actions = performanceRecords.filter(r => r.type === 'action')
                
                if (mutations.length > 0) {
                    stats.mutationStats.count = mutations.length
                    stats.mutationStats.totalTime = mutations.reduce((sum, r) => sum + r.duration, 0)
                    stats.mutationStats.averageTime = stats.mutationStats.totalTime / mutations.length
                }
                
                if (actions.length > 0) {
                    stats.actionStats.count = actions.length
                    stats.actionStats.totalTime = actions.reduce((sum, r) => sum + r.duration, 0)
                    stats.actionStats.averageTime = stats.actionStats.totalTime / actions.length
                }
            }
            
            return stats
        }
        
        // 清除性能记录
        store.clearPerformanceRecords = () => {
            performanceRecords.length = 0
        }
        
        // 获取慢操作记录
        store.getSlowOperations = () => {
            return performanceRecords
                .filter(record => record.duration > threshold)
                .sort((a, b) => b.duration - a.duration)
        }
        
        function addRecord(type, name, duration, payload = null) {
            const record = {
                type,
                name,
                duration: parseFloat(duration.toFixed(2)),
                timestamp: new Date(),
                payload
            }
            
            performanceRecords.push(record)
            
            // 保持记录数量在限制内
            if (performanceRecords.length > maxRecords) {
                performanceRecords.shift()
            }
            
            // 检查是否为慢操作
            if (duration > threshold) {
                logger.warn(
                    `🐌 慢${type}操作检测: ${name} 耗时 ${duration.toFixed(2)}ms`,
                    payload ? { payload } : ''
                )
                
                if (onSlowOperation) {
                    onSlowOperation(record)
                }
            }
        }
        
        // 监控mutations
        if (trackMutations) {
            store.subscribe((mutation, state) => {
                const startTime = performance.now()
                
                // 使用微任务来测量同步mutation的执行时间
                Promise.resolve().then(() => {
                    const endTime = performance.now()
                    const duration = endTime - startTime
                    addRecord('mutation', mutation.type, duration, mutation.payload)
                })
            })
        }
        
        // 监控actions
        if (trackActions) {
            const actionTimers = new Map()
            
            store.subscribeAction({
                before: (action, state) => {
                    actionTimers.set(action, performance.now())
                },
                after: (action, state) => {
                    const startTime = actionTimers.get(action)
                    if (startTime) {
                        const endTime = performance.now()
                        const duration = endTime - startTime
                        addRecord('action', action.type, duration, action.payload)
                        actionTimers.delete(action)
                    }
                },
                error: (action, state, error) => {
                    const startTime = actionTimers.get(action)
                    if (startTime) {
                        const endTime = performance.now()
                        const duration = endTime - startTime
                        addRecord('action', `${action.type} (ERROR)`, duration, { 
                            payload: action.payload, 
                            error: error.message 
                        })
                        actionTimers.delete(action)
                    }
                }
            })
        }
        
        // 定期报告性能统计
        if (process.env.NODE_ENV === 'development') {
            setInterval(() => {
                if (performanceRecords.length > 0) {
                    const stats = store.getPerformanceStats()
                    logger.log(
                        '📊 Vuex 性能统计:',
                        `总操作: ${stats.totalOperations}, ` +
                        `平均耗时: ${stats.averageTime.toFixed(2)}ms, ` +
                        `慢操作: ${stats.slowOperations}`
                    )
                }
            }, 30000) // 每30秒报告一次
        }
    }
}

// 使用示例：
// import createPerformancePlugin from '@/store/plugins/performance'
// 
// const performancePlugin = createPerformancePlugin({
//     threshold: 5, // 5ms为慢操作阈值
//     onSlowOperation: (record) => {
//         // 发送性能警告到监控系统
//         console.error('检测到慢操作:', record)
//     }
// })
// 
// export default new Vuex.Store({
//     // ... 其他配置
//     plugins: [performancePlugin]
// })